package com.modelscope.ai.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.modelscope.ai.domain.entity.AiEntity;
import com.modelscope.ai.domain.entity.ArticleItem;
import com.modelscope.ai.domain.entity.ChatEntity;
import com.modelscope.ai.domain.entity.R;
import com.modelscope.ai.domain.vo.ChatResult;
import com.modelscope.ai.service.AiService;
import com.modelscope.ai.service.ArticleItemService;
import com.modelscope.ai.service.ChatService;
import com.modelscope.ai.service.ExamItemService;
import com.modelscope.ai.utils.AssertUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.security.core.parameters.P;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.UUID;

@RequiredArgsConstructor
@Slf4j
@Validated
@RestController
@RequestMapping("/ai")
@Tag(name = "ai", description = "ai登录页")
public class AiController {

    final AiService aiService;
    final ChatService chatService;
    final ExamItemService examItemService;
    final ArticleItemService articleItemService;


    public void ensureDirectoryExists(Path directoryPath) throws IOException {
        if (Files.notExists(directoryPath)) {
            Files.createDirectories(directoryPath);
        }
    }

    public Path generateRandomFilePath(String baseDir, String extension) throws IOException {
        Path directoryPath = Paths.get(baseDir);

        // 使用 UUID 生成文件名
        String fileName = UUID.randomUUID().toString() + extension;

        // 可以选择性地添加日期或时间信息来创建子目录
        // 例如: /baseDir/2023/02/25/<UUID>.extension
        LocalDate date = LocalDate.now();
        String datePath = date.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        ensureDirectoryExists(Paths.get(baseDir, datePath));
        //        // 简单示例，没有日期信息
//        Path path = Paths.get(baseDir, fileName);
        return Paths.get(baseDir, datePath, fileName);
    }

    @PostMapping(value = "/chat", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public R<ChatResult> getChatResult(@RequestParam("file") MultipartFile file,
                                       @RequestParam("id") Long articleItemId,
                                       @RequestParam("uid") Long uid) {

        ArticleItem byId = articleItemService.getById(articleItemId);
        AssertUtil.isNotEmpty(byId, "id不存在");
        ChatEntity chatEntity = new ChatEntity(file, byId.getUrl(), byId.getContent());
        String json = chatService.encoder(chatEntity);
        // 返回一个得分 和回答的内容
        ObjectMapper objectMapper = new ObjectMapper();
        ChatResult chatResult = null;
        try {
            chatResult = objectMapper.readValue(json, ChatResult.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        log.info("最终得分{}", chatResult);
        // 保存考试成绩
        examItemService.add(uid, articleItemId, chatResult.getScore(), chatResult.getContent());
        return R.ok(chatResult);
    }

    @PostMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public R<String> getAiResult(@RequestParam("file") MultipartFile file,
                                 @RequestParam("model") String model,
                                 @RequestParam("confThreshold") Double confThreshold,
                                 @RequestParam("iouThreshold") Double iouThreshold) {
        //
        String base64Encoded = "";
        AiEntity aiEntity = new AiEntity(file, model, confThreshold, iouThreshold);
        log.info("传递结果->{}", aiEntity);
        log.info("图片：{} :{}图片大小:{}", file.getName(), file.getOriginalFilename(), file.getSize());

        try {
            String base64 = aiService.encoder(aiEntity);
            return R.ok("data:image/jpeg;base64," + base64);
//            log.info(base64);
//            byte[] imageBytes = Base64.getDecoder().decode(base64);
//
//            // 定位到 static 目录
//            File outputPath = new ClassPathResource("static").getFile();
//            Path filePath = generateRandomFilePath(outputPath.getAbsolutePath(), ".jpg");
//            log.info(filePath.toString());
//            log.info(outputPath.getPath());
//            try (FileOutputStream imageOutFile = new FileOutputStream(filePath.toString())) {
//                imageOutFile.write(imageBytes);
//            } catch (IOException e) {
//                throw new IOException("Error saving image", e);
//            }

//            return R.ok(filePath.toString().replace(outputPath.getAbsolutePath(), "").replace("\\", "/"));
//            // 获取文件的字节数据
//            byte[] bytes = file.getBytes();
//            // 使用Base64进行编码
//            base64Encoded = Base64.getEncoder().encodeToString(bytes);
//            // 返回Base64编码的字符串
//            return aiService.encoder(base64Encoded, model, confThreshold, iouThreshold);
        } catch (Exception e) {
            // 异常处理
            e.printStackTrace();
            return R.error("Error during file processing");
        }
    }
}
